package cn.tsmchina.one.controller.m;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.tsmchina.one.domain.category.Category;
import cn.tsmchina.one.domain.config.Config;
import cn.tsmchina.one.domain.menu.Menu;
import cn.tsmchina.one.domain.product.Product;
import cn.tsmchina.one.domain.rproduct.Rcatagory;
import cn.tsmchina.one.domain.rproduct.Rproduct;
import cn.tsmchina.one.domain.user.User;
import cn.tsmchina.one.pojo.RestaurantPojo;
import cn.tsmchina.one.service.category.CategoryService;
import cn.tsmchina.one.service.config.ConfigService;
import cn.tsmchina.one.service.menu.MenuService;
import cn.tsmchina.one.service.product.ProductService;
import cn.tsmchina.one.service.rcatagory.RcatagoryService;
import cn.tsmchina.one.service.rproduct.RproductService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.ConfigUtil;
import cn.tsmchina.one.util.JsonUtil;
import cn.tsmchina.one.util.LoginUtil;
import cn.tsmchina.one.util.PayParams;
import cn.tsmchina.one.util.Return;

@Controller
public class RedController
{
	@Autowired
	private RproductService productService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private RcatagoryService rcatagoryService;	
	/**
	 * 店铺列表信息查询
	 * @param model
	 * add by hy
	 * @return
	 */
	@RequestMapping("/rcategory")
	public String r_category(Model model, HttpServletRequest request)
	{
		System.out.println("进入红客会");
		try
		{
			long cid = LoginUtil.getCustomerId(request, customerService);
			List<Rproduct> l = productService.getProducts(cid);
			List<Rcatagory> rg = rcatagoryService.getRcatagoris(1);//暂时不考虑多页的情况
			
			List<RedCategoryPojo> pojos = new ArrayList<RedCategoryPojo>();
			for(Rcatagory rc :rg){
				RedCategoryPojo rpojo = new RedCategoryPojo();
				rpojo.setId(rc.getId());
				rpojo.setName(rc.getCatagoryName());
				rpojo.setImages(rc.getImages());
				pojos.add(rpojo);
			}
			model.addAttribute("rcategories", pojos);
		} catch (Exception e)
		{
			e.printStackTrace();
			request.setAttribute("len", 0);
		}
		
		//十个0表示红客会id，任意点一个种类，则切换店铺id
		//request.getSession().setAttribute("currentRestaurantId", "0000000000");
		return "m/rCategory";
	}
	
	/**
	 * 分类下的所有商品
	 * @param model
	 * add by hy
	 * @return
	 */
	@RequestMapping("/rfoods/{id}")
	public String list_rFoods(@PathVariable("id")int id, HttpServletRequest request)
	{
		String categoryName = "";
		categoryName = rcatagoryService.getProduct(id).getCatagoryName();
		int page = 1;
		String curPage = request.getParameter("page");
		if(!StringUtils.isEmpty(curPage)){
			page = Integer.valueOf(curPage);
		}
		long cid = LoginUtil.getCustomerId(request, customerService);
		
		
		request.setAttribute("id", id);
		//List<Rproduct> foods = productService.getFoodsByCategory(id, page);
		List<Rproduct> foods = productService.getFoodsByCategoryName(categoryName, page);
		request.setAttribute("foods", foods);
		
		List<String> productsJson = new ArrayList<String>();
		for (Rproduct product : foods) {
			Map<String, Object> data = new HashMap<>();
			data.put("id", product.getId());
			data.put("name", product.getProductName());
			data.put("price",product.getPrice());
			data.put("number", 1);
			data.put("images", product.getImages());
			data.put("restaurant", "红客会");
			productsJson.add(JsonUtil.parseJson(data));
		}
		
		//int total = productService.getFoodsCountByCategory(id);
		int total = productService.getFoodsCountByCategoryName(categoryName);
		if(total<=C.Paging.RED_PAGE_SIZE) {
			request.setAttribute("enablePage", false);
		} else {
			request.setAttribute("enablePage", true);
			if(page==1) {
				request.setAttribute("enableFirst", false);
			} else {
				request.setAttribute("enableFirst", true);
				request.setAttribute("prev", page-1);
			}
			
			int pageTotal = total % C.Paging.RED_PAGE_SIZE == 0 ? total / C.Paging.RED_PAGE_SIZE : total / C.Paging.RED_PAGE_SIZE + 1;
			if(page>=pageTotal) {
				request.setAttribute("enableLast", false);
			} else {
				request.setAttribute("enableLast", true);
				request.setAttribute("next", page+1);
			}
		}
		
		request.setAttribute("pjsons", productsJson);
		
		return "m/listrFoods";
	}	

	@RequestMapping("/rdetail/{id}.html")
	public String detail(@PathVariable("id") long id,Model model,HttpServletRequest request)
	{
		Rproduct rproduct = productService.getProduct(id);
		if(rproduct==null)
			return "m/404";
		Map<String, Object> data = new HashMap<>();
		data.put("id", rproduct.getId());
		data.put("name", rproduct.getProductName());
		data.put("price",rproduct.getPrice());
		data.put("number", 1);
		data.put("images", rproduct.getImages());
		//data.put("", value)
		model.addAttribute("p", rproduct);
		model.addAttribute("product", JsonUtil.parseJson(data));
		model.addAttribute("title", rproduct.getProductName());
		
		return "m/rdetail";
	}
	
	/**
	 * footer框，页面跳转界面
	 * @param model
	 * add by hy
	 * @return
	 */
	@RequestMapping("/rselect")
	public String r_select(Model model, HttpServletRequest request){
		
		return "m/rselect";
	}
	
	//红客会购物车
	@RequestMapping("/redcart")
	public String cart(HttpServletRequest request)
	{
		User user = (User) request.getSession().getAttribute("user");
		if(user!=null) {
			request.setAttribute("credits", user.getCredits());
		} else {
			//未登录，0积分
			request.setAttribute("credits", "<a href='user/login?cid='>请登录后查看积分</a>");
		}
		return "m/cart_red";
	}
	
	//红客会订单确认
	@RequestMapping("/redOrderInfo")
	public String orderInfo(String shopInfo, double totalPrice, int pcount, HttpServletRequest request) throws UnsupportedEncodingException
	{
		User user = (User) request.getSession().getAttribute("user");
		if(user!=null) {
			request.setAttribute("host", "http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath());
			request.setAttribute("user", user);
			request.setAttribute("credits", user.getCredits());
			//稍后开启：
			if(totalPrice < 100.00){
				totalPrice = totalPrice + 10;
			}
			request.setAttribute("totalPrice", totalPrice);
			request.setAttribute("pcount", pcount);
			shopInfo = java.net.URLDecoder.decode(shopInfo, "utf-8");
			request.setAttribute("shopInfo", shopInfo);
		}
		//微信支付添加
		Config wcpay = configService.getConfig(1, C.ConfigKeys.WC_PAY);
		if(null!=wcpay){
			request.setAttribute("wcpay", "yes");
			request.setAttribute("wcpayNotifyUrl", ConfigUtil.get("wcpayNotifyUrl"));
			
			PayParams wxpay = JsonUtil.parseObject(PayParams.class, wcpay.getConfigValue());
			request.setAttribute("wxpay", wxpay);
		}
		return "m/orderInfo_red";
	}		
	
}
